package com.blb.common.util;

import com.blb.common.entity.User;
import com.fasterxml.jackson.core.JsonProcessingException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.RedisTemplate;

import java.util.concurrent.TimeUnit;

@Slf4j
public class UserTokenUtils {

    public static final String TOKEN_PREFIX = "refresh-token:";

    public static final Integer REFRESH_TOKEN_EXPIRE = JwtUtils.EXPIRE_MINUTES * 12;

    public static ResponseResult<User> generateUserToken(User user, RedisTemplate<String,String > redisTemplate) throws JsonProcessingException {
        //生成access token字符串
        String accessToken = JwtUtils.generateUserToken(user, RsaUtils.privateKey, JwtUtils.EXPIRE_MINUTES);
        //用accessToken的一部分生成refreshToken
        String refresh = accessToken.substring(0,20);
        //生成refresh token字符串
        String refreshToken = JwtUtils.generateStringToken(refresh, RsaUtils.privateKey, REFRESH_TOKEN_EXPIRE);
        log.info("生成access token：{}",accessToken);
        log.info("生成refresh token：{}",refreshToken);
        //保存refresh token和userid到redis
        redisTemplate.opsForValue().set(TOKEN_PREFIX + refresh, String.valueOf(user.getId()), REFRESH_TOKEN_EXPIRE, TimeUnit.MINUTES);
        return ResponseResult.ok(user,accessToken,refreshToken);
    }
}
